import time
from requests_html import HTMLSession
from lib.conf.config import settings
from src.plugins import PluginManager
from concurrent.futures import ThreadPoolExecutor
from hashlib import md5


class Base:
    def post_asset(self, server_info):
        """
        向后端django服务器发送采集完的数据
        :param server_info: 采集完毕的数据，需要是一个字典
        :return: None
        """
        session = HTMLSession()
        session.post(settings.API, json=server_info, headers={
            'AUTHENTICATION': self.get_key()
        })

    def get_key(self):
        key_one = md5()
        new_time = time.time()
        auth_key = settings.AUTH_KEY
        key_one.update(auth_key.encode('utf8'))
        encrypted_string_one = key_one.hexdigest() + '|' + str(new_time)
        key_twe = md5(encrypted_string_one.encode('utf8'))
        encrypted_string_twe = key_twe.hexdigest() + '|' + str(new_time)
        return encrypted_string_twe


class Agent(Base):

    def execute(self):
        server_info = PluginManager().exec_plugin()
        new_hostname = server_info['basic']['data']['hostname']

        with open(settings.HOST_FILE, 'r', encoding='utf-8') as f:
            old_hostname = f.read(1024)

        if not old_hostname:
            with open(settings.HOST_FILE, 'w', encoding='utf-8') as f:
                f.write(new_hostname)
        else:
            server_info['basic']['data']['hostname'] = old_hostname

        self.post_asset(server_info)


class SshSalt(Base):

    def get_host(self):
        session = HTMLSession()
        # 向django服务器获取机器列表
        response = session.get(settings.API)
        # 返回一个JSON列表
        result = response.json()
        if not result['status']:
            return
        # 返回一个包含了所有服务器IP地址的字典
        return result['data']

    def run(self, host):
        server_info = PluginManager(host).exec_plugin()
        self.post_asset(server_info)

    def execute(self):
        host_list = self.get_host()
        pool = ThreadPoolExecutor()
        for name, host in host_list.items():
            pool.submit(self.run, host)
